package com.jb.repair.acticity;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.adapter.TreeLedgerAdapter;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.common.DialogCallBack;
import com.jb.repair.dao.Db;
import com.jb.repair.dao.InsertDb;
import com.jb.repair.dao.LocalDbDao;
import com.jb.repair.dao.ModifyDb;
import com.jb.repair.fragment.CheckFragment;
import com.jb.repair.fragment.DocFrament;
import com.jb.repair.fragment.LedgerFrament;
import com.jb.repair.fragment.MainFragment;
import com.jb.repair.fragment.NullFrament;
import com.jb.repair.fragment.RegularFragment;
import com.jb.repair.fragment.SettingFragment;
import com.jb.repair.listener.TreeListener;
import com.jb.repair.model.FileLbModel;
import com.jb.repair.model.LedgerModel;
import com.jb.repair.model.LedgerModelTest;
import com.jb.repair.model.QxjlModel;
import com.jb.repair.model.ResultModel;
import com.jb.repair.model.ResultStatisticModel;
import com.jb.repair.model.SbccModel;
import com.jb.repair.model.SbsModel;
import com.jb.repair.model.TaskModel;
import com.jb.repair.model.UpdateCheck4Json;
import com.jb.repair.model.UpdateLedger4Json;
import com.jb.repair.model.User4Json;
import com.jb.repair.model.YcjlModel;
import com.jb.repair.net.HttpClient;
import com.jb.repair.net.HttpCookies;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.util.NetUtil;
import com.jb.repair.view.AutoChangeLineLinerLayout;
import com.jb.repair.view.AutoRelativeLayout;
import com.jb.repair.view.TitleView;
import com.slidingmenu.lib.SlidingMenu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends BaseActivity implements View.OnClickListener, DialogCallBack, SettingFragment.NotifyParentActivity {

    private View rightMenuView, rightMenuView2;
    private TextView tv_username;
    private TitleView titleView;
    private SlidingMenu slideMenu;
    private EditText ed_search;
    private Button btn_search;
    private TextView tv_update_time;
    public LayoutInflater mInflater;

    private final int UPLOAD = 1;
    private final int REPEAT = 2;
    private final int UPDATE = 3;
    private final int UPLOAD_EXIT = 5;
    private final int LOGIN_VALIDATA_DIALOG = 6;
    private final int NO_NET_DIALOG = 7;
    private SharedPreferences sp;
    private List<ResultModel> upLoadResultList;
    private List<YcjlModel> upLoadabnormalList;
    private List<QxjlModel> upLoadDefectList;
    private List<FileLbModel> upLoadFileList;
    private List<FileLbModel> fileList;
    private LocalDbDao dao;
    private Gson gson = new Gson();
    private Boolean isFirstFoucs = true;  //页面是否第一次获取焦点
    private Db db;
    private String textId;
    private List<String> childList = new ArrayList<>();

    private static final String TAG = "MainActivity";
    private AutoChangeLineLinerLayout ll_first;
    private AutoChangeLineLinerLayout ll_second;
    private AutoChangeLineLinerLayout ll_third;
    private LinearLayout rl;
    private LinearLayout rl2;
    private LinearLayout rl3;
    private LinearLayout rl4;

    private Spinner spiPro;
    private EditText etPerson;
    private DatePicker dpCreatStart, dpCreatEnd, dpFinishStart, dpFinishEnd;
    private Spinner spiStatus;
    private Button btnQuery;

    private ArrayList<LedgerModelTest> sbsModelsP = new ArrayList<>();
    private ArrayList<LedgerModelTest> sbsModelsC = new ArrayList<>();
    private ArrayList<LedgerModelTest> sbsModels = new ArrayList<>();
    private SbccModel sbcc;
    private int flag_update = 0;
    private int choose = -1;//1-只同步点检数据 2-只同步台账数据 3- 都不同步 0-都同步

    private List<TaskModel> taskModelList;

    private MainFragment mainFragment;
    private LedgerFrament ledgerFrament;
    private RegularFragment regularFragment;
    private CheckFragment checkFragment;
    private DocFrament docFrament;
    private SettingFragment settingFragment;
    private NullFrament nullFrament;
    private OnMainListener onMainListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.mInflater = LayoutInflater.from(this);
        sp = getSharedPreferences(Constants.SP_NAME, MODE_PRIVATE);
        db = Db.getInstance(this);
        dao = LocalDbDao.getInstance(this);
        initMenu();
        initView();
        switchToMain();
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "onResume()");
        super.onResume();
        upLoadabnormalList = dao.getAllAbnormal();
        upLoadDefectList = dao.getAllDefect();
        upLoadFileList = dao.getAllFile();
        isFirstFoucs = true;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        Log.i(TAG, "onWindowFocusChanged execute " + hasFocus);
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && isFirstFoucs) {
            if (NetUtil.isNetOK(getApplicationContext()))
                if (LocalDbDao.getInstance(getApplicationContext()).hasData()) {
                    MessageUtil.showPopDialog(getApplicationContext(), titleView, "上传", "有未上传结果，是否上传", "确定", UPLOAD, this);
                    isFirstFoucs = false;
                }
        }
    }

    private void initView() {
        titleView = (TitleView) findViewById(R.id.titleView);
        /* 初始化fragment */
        mainFragment = new MainFragment();
        ledgerFrament = new LedgerFrament();
        regularFragment = RegularFragment.newInstance();
        checkFragment = new CheckFragment();
        docFrament = new DocFrament();
        settingFragment = new SettingFragment();
        nullFrament = new NullFrament();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void showFragment(Fragment f) {
        FragmentTransaction ft = this.getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_content, f);
        ft.commit();
        slideMenu.setStatic(false);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        Log.i(TAG, "onAttachFragment");
        String fragmentName = fragment.getClass().getSimpleName();
        try {
            if (fragmentName.equals("RegularFragment"))
                onMainListener = (OnMainListener) fragment;
        } catch (Exception e) {
            throw new ClassCastException(this.toString() + " must implementOnMainListener");
        }
        super.onAttachFragment(fragment);
    }

    // 接口
    public interface OnMainListener {
        public void onMainAction(Map params);
    }

    public void addImage(AutoChangeLineLinerLayout ll) {
        ImageView image = new ImageView(this);
        image.setBackgroundResource(R.drawable.circle);
        ll.addView(image);
    }

    private void initMenu() {
        //左侧侧滑菜单
        final View leftMenuView = LayoutInflater.from(this).inflate(R.layout.menu_left, null);
        //右侧滑菜单
        rightMenuView = LayoutInflater.from(this).inflate(R.layout.menu_right, null);
        rightMenuView2 = LayoutInflater.from(this).inflate(R.layout.menu_right_regular, null);
//        spiPro = (Spinner)rightMenuView2.findViewById(R.id.spi_profession);
//        etPerson = (EditText)rightMenuView2.findViewById(R.id.et_person);
        dpCreatStart = (DatePicker) rightMenuView2.findViewById(R.id.dp_creat_start);
        dpCreatEnd = (DatePicker) rightMenuView2.findViewById(R.id.dp_creat_end);
        dpFinishStart = (DatePicker) rightMenuView2.findViewById(R.id.dp_finish_start);
        dpFinishEnd = (DatePicker) rightMenuView2.findViewById(R.id.dp_finish_end);
        spiStatus = (Spinner) rightMenuView2.findViewById(R.id.spi_status);
        //查询按钮监听
        btnQuery = (Button) rightMenuView2.findViewById(R.id.btn_query);
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String, String> map = new HashMap<>();
                map.put("creat_start_date", dpCreatStart.getYear() + "-" + (dpCreatStart.getMonth() + 1) + "-" + dpCreatStart.getDayOfMonth());
                map.put("creat_end_date", dpCreatEnd.getYear() + "-" + (dpCreatEnd.getMonth() + 1) + "-" + dpCreatEnd.getDayOfMonth());
                map.put("finish_start_date", dpFinishStart.getYear() + "-" + (dpFinishStart.getMonth() + 1) + "-" + dpFinishStart.getDayOfMonth());
                map.put("finish_end_date", dpFinishEnd.getYear() + "-" + (dpFinishEnd.getMonth() + 1) + "-" + dpFinishEnd.getDayOfMonth());
                try {
                    JSONObject jsonObject = new JSONObject(Constants.CT_TASK_STATUS_NAME);
                    map.put("status", jsonObject.getString(spiStatus.getSelectedItem().toString().trim()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //发送给 RegularFragment
                onMainListener.onMainAction(map);
                //查询页面隐藏
                slideMenu.setStatic(false);
            }
        });

        slideMenu = new SlidingMenu(this);

        slideMenu.setMode(SlidingMenu.LEFT_RIGHT);
        //设置触摸屏幕的模式
        slideMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        //设置滑动菜单视图的宽度
        slideMenu.setBehindOffsetRes(R.dimen.x200);
        //设置渐入渐出的效果值
        slideMenu.setFadeDegree(0.35f);
        slideMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        slideMenu.setMenu(leftMenuView);
        slideMenu.setSecondaryMenu(rightMenuView);
        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_username.setText(sp.getString(Constants.PERSON_NAME, ""));
        //为侧滑菜单中的空间设置监听
        leftMenuView.findViewById(R.id.ll_check).setOnClickListener(this);
        leftMenuView.findViewById(R.id.ll_task).setOnClickListener(this);
        leftMenuView.findViewById(R.id.ll_exit).setOnClickListener(this);
        leftMenuView.findViewById(R.id.ll_regular_work).setOnClickListener(this);
        leftMenuView.findViewById(R.id.ll_ledger).setOnClickListener(this);
        leftMenuView.findViewById(R.id.ll_setting).setOnClickListener(this);
        leftMenuView.findViewById(R.id.ll_doc).setOnClickListener(this);
        ll_first = (AutoChangeLineLinerLayout) rightMenuView.findViewById(R.id.ll_first);
        ll_second = (AutoChangeLineLinerLayout) rightMenuView.findViewById(R.id.ll_second);
        ll_third = (AutoChangeLineLinerLayout) rightMenuView.findViewById(R.id.ll_third);
        rl = (LinearLayout) rightMenuView.findViewById(R.id.ll_ll);
        rl2 = (LinearLayout) rightMenuView.findViewById(R.id.ll_ll2);
        rl3 = (LinearLayout) rightMenuView.findViewById(R.id.ll_ll3);
        rl4 = (LinearLayout) rightMenuView.findViewById(R.id.ll_ll4);

//--------------------------------------------------------分割线以下----------------------------------------------204-719
        //12.29 zhangjin
        //获取发电厂顶层layer_code
        textId = db.getName("layer_code", "TB_EQ_NAV", "layer_type", "0500301");

        //获取专业层集合
        final List<SbsModel> layerChild = db.getSbsModelByparentid(this.textId);
        layerChild.add(addSbsModel());

        sbsModelsC = new ArrayList<>();
        sbsModelsP = new ArrayList<>();

        for (final SbsModel s : layerChild) {
            //动态生成textview
            final TextView tv = new TextView(this);
            setAll(tv);
            tv.setText(s.layer_name);
            ll_first.addView(tv);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //如果点击的是第一层的全部按钮
                    ed_search.setText("");
                    if (s.guid.equals("123123")) {
                        //创建一个可以交互的设备树
                        sbsModelsC.clear();
                        sbsModelsP.clear();
                        sbsModelsP = getSbsModelsP(MainActivity.this.textId);
                        List<SbsModel> sbsModelList = db.getSbsModelByparentid(MainActivity.this.textId);
                        getAll(sbsModelList);
                        //修改布局
                        singleBackground(ll_first);
                        v.setBackgroundResource(R.drawable.textview_selected);
                        ll_second.removeAllViews();
                        addImage(ll_second);
                        ll_third.removeAllViews();
                        addImage(ll_third);
                        rl.removeAllViews();
                        rl2.removeAllViews();
                        rl3.removeAllViews();
                        rl4.removeAllViews();

                        //设备树层的适配器
                        TreeLedgerAdapter treeLedgerAdapter = new TreeLedgerAdapter(sbsModelsP, sbsModelsC, MainActivity.this, new TreeLedgerAdapter.JumpFragment() {
                            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                            @Override
                            public void toFragment(LedgerModelTest ledgerModelTest) {
                                super.toFragment(ledgerModelTest);
                                titleView.setTitle("设备台账");
                                titleView.setRightTextViewVisable(false);
                                titleView.setRightImageViewVisibility(View.VISIBLE);
                                titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                                    @Override
                                    public void onRightImage1Click(View view) {
                                        super.onRightImage1Click(view);
                                        slideMenu.showSecondaryMenu();
                                    }

                                    @Override
                                    public void onLeftImageClick(View view) {
                                        super.onLeftTextClick(view);
                                        slideMenu.showMenu();
                                    }
                                });
                                slideMenu.setStatic(false);
                                FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                                LedgerFrament f = new LedgerFrament();
                                Bundle b = new Bundle();
                                b.putString("layer_code", ledgerModelTest.getContentText().layer_code);
                                b.putString("name", ledgerModelTest.getContentText().layer_name);
                                f.setArguments(b);
                                ft.replace(R.id.fragment_content, f);
                                ft.commit();

                            }
                        });
                        //设备树条目的点击事件
                        TreeListener treeListener = new TreeListener(treeLedgerAdapter, MainActivity.this, new TreeListener.UpdateView() {
                            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                            @Override
                            public void update(LedgerModelTest ledgerModelTest) {
                                super.update(ledgerModelTest);
                                titleView.setTitle("设备台账");
                                slideMenu.setStatic(false);
                                titleView.setRightTextViewVisable(false);
                                titleView.setRightImageViewVisibility(View.VISIBLE);
                                titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                                    @Override
                                    public void onRightImage1Click(View view) {
                                        super.onRightImage1Click(view);
                                        slideMenu.showSecondaryMenu();
                                    }

                                    @Override
                                    public void onLeftImageClick(View view) {
                                        super.onLeftTextClick(view);
                                        slideMenu.showMenu();
                                    }
                                });
                                FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                                LedgerFrament f = new LedgerFrament();
                                Bundle b = new Bundle();
                                b.putString("id", ledgerModelTest.getContentText().guid);
//                                Log.e("sbsbsb", ledgerModelTest.getContentText().guid);
//                                Log.e("sbsbsb", "从设备的guid跳转");
                                b.putString("name", ledgerModelTest.getContentText().layer_name);
                                f.setArguments(b);
                                ft.replace(R.id.fragment_content, f);
                                ft.commit();
                            }
                        });
                        //动态生成一个listview用于展示
//                        ListViewInScroll list1 = new ListViewInScroll(MainActivity.this);
//                        rl.addView(list1);
//                        list1.setAdapter(treeLedgerAdapter);
//                      list1.setOnItemClickListener(treeListener);

                        //测试普通listview能不能响应点击事件
                        ListView listView = new ListView(MainActivity.this);
                        rl4.addView(listView);
                        listView.setAdapter(treeLedgerAdapter);
                        listView.setOnItemClickListener(treeListener);

                        return;
                    }
                    //如果点击的不是第一层的全部按钮，那么点击的是专业按钮
                    //点击第一层次 消除第三层次
                    ll_third.removeAllViews();
                    addImage(ll_third);
                    //这个地方用于设备层的显示 未用
                    sbcc = new SbccModel();
                    sbcc.setName1(tv.getText().toString());
                    //设置选中textview的背景
                    singleBackground(ll_first);
                    v.setBackgroundResource(R.drawable.textview_selected);
                    //点击动态添加布局
                    rl.removeAllViews();
                    rl2.removeAllViews();
                    rl3.removeAllViews();
                    rl4.removeAllViews();
                    autoCreateRL(R.drawable.first, 0, s.layer_name, true, true, rl, s);
                    //添加第二层的按钮
                    ll_second.removeAllViews();
                    addImage(ll_second);
                    final List<SbsModel> layerChild2 = db.getSbsModelByparentid(s.layer_code);
                    layerChild2.add(addSbsModel());
                    for (final SbsModel s : layerChild2) {
                        final TextView tv = new TextView(MainActivity.this);
                        setAll(tv);
                        tv.setText(s.layer_name);
                        ll_second.addView(tv);
                        tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //点击第二层全部按钮的处理逻辑
                                if (s.guid.equals("123123")) {
                                    singleBackground(ll_second);
                                    v.setBackgroundResource(R.drawable.textview_selected);
                                    ll_third.removeAllViews();
                                    addImage(ll_third);
                                    rl2.removeAllViews();
                                    rl3.removeAllViews();
                                    rl4.removeAllViews();
                                    for (final SbsModel s : layerChild2) {
                                        if (!s.guid.equals("123123")) {
                                            AutoRelativeLayout autoRelativeLayout = autoCreateRL(R.drawable.second, 40, s.layer_name, true, true, rl2, s);
                                            autoRelativeLayout.setOnClickListener(new AutoRelativeLayout.OnRightTextClickListener() {
                                                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                                                @Override
                                                public void OnRightTextClick(View view) {
                                                    super.OnRightTextClick(view);
                                                    titleView.setTitle("设备台账");
                                                    slideMenu.setStatic(false);
                                                    titleView.setRightTextViewVisable(false);
                                                    titleView.setRightImageViewVisibility(View.VISIBLE);
                                                    titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                                                        @Override
                                                        public void onLeftImageClick(View view) {
                                                            super.onLeftImageClick(view);
                                                            slideMenu.showMenu();
                                                        }

                                                        @Override
                                                        public void onRightImage1Click(View view) {
                                                            super.onLeftTextClick(view);
                                                            slideMenu.showSecondaryMenu();
                                                        }
                                                    });
                                                    FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                                                    LedgerFrament f = new LedgerFrament();
                                                    Bundle b = new Bundle();
                                                    b.putString("layer_code", s.layer_code);
//                                                    Log.e("sbsbsb", s.layer_name);
//                                                    Log.e("sbsbsb", "层次编码跳转");
                                                    b.putString("name", s.layer_name);
                                                    f.setArguments(b);
                                                    ft.replace(R.id.fragment_content, f);
                                                    ft.commit();
                                                }
                                            });
                                        }
                                    }
                                    return;
                                }
                                //点击尝试添加布局
                                rl2.removeAllViews();
                                rl3.removeAllViews();
                                rl4.removeAllViews();
                                sbcc.setName2(tv.getText().toString());
                                autoCreateRL(R.drawable.second, 40, s.layer_name, true, true, rl2, s);
                                singleBackground(ll_second);
                                v.setBackgroundResource(R.drawable.textview_selected);
                                ll_third.removeAllViews();
                                addImage(ll_third);
                                final List<SbsModel> layerChild3 = db.getSbsModelByparentid(s.layer_code);
                                layerChild3.add(addSbsModel());
                                for (final SbsModel s : layerChild3) {
                                    final TextView tv = new TextView(MainActivity.this);
                                    setAll(tv);
                                    tv.setText(s.layer_name);
                                    ll_third.addView(tv);
                                    tv.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            //点击第三层全部显示的逻辑
                                            if (s.guid.equals("123123")) {
                                                singleBackground(ll_third);
                                                v.setBackgroundResource(R.drawable.textview_selected);
                                                rl3.removeAllViews();
                                                rl4.removeAllViews();
                                                for (final SbsModel s : layerChild3) {
                                                    if (!s.guid.equals("123123")) {
                                                        AutoRelativeLayout autoRelativeLayout = autoCreateRL(R.drawable.third, 60, s.layer_name, true, true, rl3, s);
                                                        autoRelativeLayout.setOnClickListener(new AutoRelativeLayout.OnRightTextClickListener() {
                                                            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                                                            @Override
                                                            public void OnRightTextClick(View view) {
                                                                super.OnRightTextClick(view);

                                                                titleView.setTitle("设备台账");
                                                                slideMenu.setStatic(false);
                                                                titleView.setRightTextViewVisable(false);
                                                                titleView.setRightImageViewVisibility(View.VISIBLE);
                                                                titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                                                                    @Override
                                                                    public void onRightImage1Click(View view) {
                                                                        super.onRightImage1Click(view);
                                                                        slideMenu.showSecondaryMenu();
                                                                    }

                                                                    @Override
                                                                    public void onLeftImageClick(View view) {
                                                                        super.onLeftTextClick(view);
                                                                        slideMenu.showMenu();
                                                                    }
                                                                });
                                                                FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                                                                LedgerFrament f = new LedgerFrament();
                                                                Bundle b = new Bundle();
                                                                b.putString("layer_code", s.layer_code);
                                                                Log.e("sbsbsb", s.layer_name);
                                                                Log.e("sbsbsb", "层次编码跳转");
                                                                b.putString("name", s.layer_name);
                                                                f.setArguments(b);
                                                                ft.replace(R.id.fragment_content, f);
                                                                ft.commit();
                                                            }
                                                        });
                                                    }
                                                }
                                                return;
                                            }
                                            //点击尝试添加布局
                                            rl3.removeAllViews();
                                            rl4.removeAllViews();
                                            sbcc.setName3(tv.getText().toString());
                                            autoCreateRL(R.drawable.third, 60, s.layer_name, true, true, rl3, s);
                                            singleBackground(ll_third);
                                            v.setBackgroundResource(R.drawable.textview_selected);
                                            drawAll(s);
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        ed_search = (EditText) rightMenuView.findViewById(R.id.search_et);
        btn_search = (Button) rightMenuView.findViewById(R.id.btn_search);
        tv_update_time = (TextView) leftMenuView.findViewById(R.id.tv_data_update_time);
        tv_update_time.setText("点检数据更新于：" + F1Application.getDbUpdateDate(F1Application.getUserId()));

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = ed_search.getText().toString().trim();
                if (key == null || key.equals("")) {
                    MessageUtil.showToast(getApplicationContext(), "输入内容不能为空");
                    return;
                }

                //模糊查询
                sbsModelsC.clear();
                sbsModelsP.clear();
                sbsModelsP = getSbsModelsP(MainActivity.this.textId);
                List<SbsModel> sbsModelList = db.getSbsModelByparentid(MainActivity.this.textId);
                getAll(sbsModelList);
                singleBackground(ll_first);
                ll_second.removeAllViews();
                addImage(ll_second);
                ll_third.removeAllViews();
                addImage(ll_third);
                rl.removeAllViews();
                rl2.removeAllViews();
                rl3.removeAllViews();
                rl4.removeAllViews();
                //查询匹配的模型加入集合
                sbsModels.clear();
                childList.clear();
                int i = 0;
                for (LedgerModelTest ledgerModelTest : sbsModelsC) {
                    if (!ledgerModelTest.isHasChildren()) {
                        String layer_name = ledgerModelTest.getContentText().getLayer_name();
                        if (layer_name.contains(key)) {
                            //      Log.e("1229", "可以判断相符" + layer_name + ledgerModelTest.isHasChildren());
                            i++;
                            if (!sbsModels.contains(ledgerModelTest)) {
                                sbsModels.add(ledgerModelTest);
                            }
                            if (!childList.contains(ledgerModelTest.getParentId())) {
                                childList.add(ledgerModelTest.getParentId());
                            }
                        }
                    }
                }
                //递归
                for (int j = 0; j < 10; j++) {
                    for (LedgerModelTest ledgerModelTest : sbsModelsC) {
                        if (ledgerModelTest.isHasChildren() && childList.contains(ledgerModelTest.getLayerCode())) {
                            if (!sbsModels.contains(ledgerModelTest)) {
                                sbsModels.add(ledgerModelTest);
                            }
                            if (!childList.contains(ledgerModelTest.getParentId())) {
                                childList.add(ledgerModelTest.getParentId());
                            }
                        }
                        ;
                    }
                }
                TextView textView = new TextView(MainActivity.this);
                rl.addView(textView);
                textView.setGravity(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundResource(R.drawable.textview_unselet);
                textView.setText("共查询到" + i + "条记录");

                ListView list2 = new ListView(MainActivity.this);
                rl4.addView(list2);

                TreeLedgerAdapter treeLedgerAdapter1 = new TreeLedgerAdapter(sbsModelsP, sbsModels, MainActivity.this, new TreeLedgerAdapter.JumpFragment() {
                    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public void toFragment(LedgerModelTest ledgerModelTest) {
                        super.toFragment(ledgerModelTest);
                        titleView.setTitle("设备台账");
                        slideMenu.setStatic(false);
                        titleView.setRightTextViewVisable(false);
                        titleView.setRightImageViewVisibility(View.VISIBLE);
                        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                            @Override
                            public void onRightImage1Click(View view) {
                                super.onRightImage1Click(view);
                                slideMenu.showSecondaryMenu();
                            }

                            @Override
                            public void onLeftImageClick(View view) {
                                super.onLeftTextClick(view);
                                slideMenu.showMenu();
                            }
                        });
                        FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                        LedgerFrament f = new LedgerFrament();
                        Bundle b = new Bundle();
                        b.putString("layer_code", ledgerModelTest.getContentText().layer_code);
                        Log.e("sbsbsb", ledgerModelTest.getContentText().layer_code);
                        Log.e("sbsbsb", "从层次编码跳转");
                        b.putString("name", ledgerModelTest.getContentText().layer_name);
                        f.setArguments(b);
                        ft.replace(R.id.fragment_content, f);
                        ft.commit();
                    }
                });
                TreeListener treeListener1 = new TreeListener(treeLedgerAdapter1, MainActivity.this, new TreeListener.UpdateView() {
                    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public void update(LedgerModelTest ledgerModelTest) {
                        super.update(ledgerModelTest);
                        titleView.setTitle("设备台账");
                        slideMenu.setStatic(false);
                        titleView.setRightTextViewVisable(false);
                        titleView.setRightImageViewVisibility(View.VISIBLE);
                        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                            @Override
                            public void onRightImage1Click(View view) {
                                super.onRightImage1Click(view);
                                slideMenu.showSecondaryMenu();

                            }

                            @Override
                            public void onLeftImageClick(View view) {
                                super.onLeftTextClick(view);
                                slideMenu.showMenu();
                            }
                        });
                        FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                        LedgerFrament f = new LedgerFrament();
                        Bundle b = new Bundle();
                        b.putString("id", ledgerModelTest.getContentText().guid);
                        Log.e("sbsbsb", ledgerModelTest.getContentText().guid);
                        Log.e("sbsbsb", "从设备的guid跳转");
                        b.putString("name", ledgerModelTest.getContentText().layer_name);
                        f.setArguments(b);
                        ft.replace(R.id.fragment_content, f);
                        ft.commit();
                    }
                });
                list2.setAdapter(treeLedgerAdapter1);
                list2.setOnItemClickListener(treeListener1);
            }
        });
    }

    //创建一个全部的按钮model
    public SbsModel addSbsModel() {
        SbsModel model = new SbsModel();
        model.layer_name = "全部";
        model.guid = "123123";
        return model;
    }

    //文本框的样式
    public void setAll(TextView tv) {
        tv.setBackgroundResource(R.drawable.textview_unselet);
        tv.setTextColor(getResources().getColor(R.color.black_text));
        tv.setTextSize(getResources().getDimension(R.dimen.right_textSize));
    }

    //拿到顶层设备树分层
    public ArrayList<LedgerModelTest> getSbsModelsP(String id) {
        List<SbsModel> list = db.getSbsModelByparentid(id);
        if (list != null && !list.isEmpty()) {
            for (SbsModel model : list) {
                LedgerModelTest ledgerModelTest = new LedgerModelTest(model, LedgerModelTest.TOP_LEVEL, model.guid, LedgerModelTest.NO_PARENT, true, false, model.layer_code);
                sbsModelsP.add(ledgerModelTest);
            }
            return sbsModelsP;
        }
        return null;
    }

    //拿到其他层级的分层信息
    public void getAll(List<SbsModel> list) {
        for (SbsModel sbsModel : list) {
            List<SbsModel> layerChild2 = db.getSbsModelByparentid(sbsModel.layer_code);
            if (layerChild2 != null && !layerChild2.isEmpty()) {
                //如果得到的集合不为空 说明需要递归
                for (SbsModel sbsModel1 : layerChild2) {
                    LedgerModelTest ledgerModelTest1 = new LedgerModelTest(sbsModel1, getParentLevel(sbsModel.guid) + 1, sbsModel1.guid, sbsModel1.parent_id, true, false, sbsModel1.layer_code);
                    sbsModelsC.add(ledgerModelTest1);
                }
                getAll(layerChild2);
            } else {
                //得到集合为空说明当前循环的集合已经是最后一层  需要添加设备名称
                List<LedgerModel> ledgerModelList = db.getLedgerModelByLayerCode(sbsModel.layer_code);
                for (LedgerModel model : ledgerModelList) {
                    SbsModel sbsModel1 = new SbsModel();
                    sbsModel1.setLayer_name(model.eq_name);
                    sbsModel1.setParent_id(sbsModel.layer_code);
                    sbsModel1.setGuid(model.guid);//把基本信息表的guid赋给sbsmodel 以便点击后传入设备台账页面
                    LedgerModelTest ledgerModelTest1 = new LedgerModelTest(sbsModel1, getParentLevel(sbsModel.guid) + 1, sbsModel1.guid, sbsModel1.parent_id, false, false, model.layer_code);
                    sbsModelsC.add(ledgerModelTest1);
                }
            }
        }
    }

    //拿到父类的level
    public int getParentLevel(String id) {
        for (LedgerModelTest ledgerModelTest : sbsModelsC) {
            if (!sbsModelsC.isEmpty()) {
                if (id.equals(ledgerModelTest.getId())) {
                    return ledgerModelTest.getLevel();
                }
            }
        }
        for (LedgerModelTest ledgerModelTest : sbsModelsP) {
            if (!sbsModelsP.isEmpty()) {
                if (id.equals(ledgerModelTest.getId())) {
                    return ledgerModelTest.getLevel();
                }
            }
        }
        return -1;
    }

    //画出所有层次
    public void drawAll(SbsModel ss) {
        List<SbsModel> list = db.getSbsModelByparentid(ss.layer_code);
        if (list != null && !list.isEmpty()) {
            for (final SbsModel sbsModel : list) {
                List<SbsModel> list1 = db.getSbsModelByparentid(sbsModel.layer_code);
                if (list1 != null && !list1.isEmpty()) {
                    autoCreateRL(R.drawable.fourth, 80, sbsModel.layer_name, true, true, rl3, sbsModel);
                    drawAll(sbsModel);
                } else {
                    //如果执行，说明是设备树中的最后一层
                    autoCreateRL(R.drawable.fourth, 80, sbsModel.layer_name, true, true, rl3, sbsModel);
                    List<LedgerModel> ledgerModelList = db.getLedgerModelByLayerCode(sbsModel.layer_code);
                    for (final LedgerModel model : ledgerModelList) {
                        AutoRelativeLayout autoRelativeLayout = autoCreateRL(R.drawable.last, 100, model.eq_name, false, false, rl3, null);
                        autoRelativeLayout.setOnClickListener(new AutoRelativeLayout.OnRightTextClickListener() {
                            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                            @Override
                            public void OnRLClick(View view) {
                                super.OnRLClick(view);
                                //跳转到设备台账界面
                                titleView.setTitle("设备台账");
                                slideMenu.setStatic(false);
                                titleView.setRightTextViewVisable(false);
                                titleView.setRightImageViewVisibility(View.VISIBLE);
                                titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                                    @Override
                                    public void onRightImage1Click(View view) {
                                        super.onRightImage1Click(view);
                                        slideMenu.showSecondaryMenu();
                                    }

                                    @Override
                                    public void onLeftImageClick(View view) {
                                        super.onLeftTextClick(view);
                                        slideMenu.showMenu();
                                    }
                                });
                                FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                                LedgerFrament f = new LedgerFrament();
                                Bundle b = new Bundle();
                                b.putString("id", model.guid);
                                Log.e("sbsbsb", model.eq_name);
                                Log.e("sbsbsb", "设备guid跳转");
                                b.putString("name", sbcc.getName1() + "→" + sbcc.getName2() + "→" + sbcc.getName3());
                                f.setArguments(b);
                                ft.replace(R.id.fragment_content, f);
                                ft.commit();
                            }
                        });
                    }
                }
            }
        } else {
            List<LedgerModel> ledgerModelList = db.getLedgerModelByLayerCode(ss.layer_code);
            for (final LedgerModel model : ledgerModelList) {
                AutoRelativeLayout autoRelativeLayout = autoCreateRL(R.drawable.last, 100, model.eq_name, false, false, rl3, null);
                autoRelativeLayout.setOnClickListener(new AutoRelativeLayout.OnRightTextClickListener() {
                    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public void OnRLClick(View view) {
                        super.OnRLClick(view);
                        //跳转到设备台账界面
                        titleView.setTitle("设备台账");
                        titleView.setRightTextViewVisable(false);
                        titleView.setRightImageViewVisibility(View.VISIBLE);
                        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                            @Override
                            public void onRightImage1Click(View view) {
                                super.onRightImage1Click(view);
                                slideMenu.showSecondaryMenu();
                            }

                            @Override
                            public void onLeftImageClick(View view) {
                                super.onLeftTextClick(view);
                                slideMenu.showMenu();
                            }
                        });
                        slideMenu.setStatic(false);
                        FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                        LedgerFrament f = new LedgerFrament();
                        Bundle b = new Bundle();
                        b.putString("id", model.guid);
                        b.putString("name", sbcc.getName1() + "→" + sbcc.getName2() + "→" + sbcc.getName3());
                        f.setArguments(b);
                        ft.replace(R.id.fragment_content, f);
                        ft.commit();
                    }
                });
            }
        }
    }

    //文本框单选的背景设置方法
    public void singleBackground(AutoChangeLineLinerLayout ll) {
        int childCount = ll.getChildCount();
        for (int i = 1; i < childCount; i++) {
            ll.getChildAt(i).setBackgroundResource(R.drawable.textview_unselet);
        }
    }

    //定义动态生成的相对布局
    public AutoRelativeLayout autoCreateRL(int backgroundStyle, int margin, String text, boolean iconVisibility, boolean tvRightVisibility, final LinearLayout linearLayout, final SbsModel sbsModel) {
        AutoRelativeLayout arl1 = new AutoRelativeLayout(this);
        arl1.setBackgroundStyle(backgroundStyle);
        arl1.setMargin(margin);
        arl1.setTv_main(text);
        arl1.setIconVisibility(iconVisibility);
        arl1.setTvRightVisibility(tvRightVisibility);
        arl1.setOnClickListener(new AutoRelativeLayout.OnRightTextClickListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void OnRightTextClick(View view) {
                titleView.setTitle("设备台账");
                titleView.setRightTextViewVisable(false);
                titleView.setRightImageViewVisibility(View.VISIBLE);
                titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
                    @Override
                    public void onRightImage1Click(View view) {
                        super.onRightImage1Click(view);
                        slideMenu.showSecondaryMenu();
                    }

                    @Override
                    public void onLeftImageClick(View view) {
                        super.onLeftTextClick(view);
                        slideMenu.showMenu();
                    }
                });
                slideMenu.setStatic(false);
                FragmentTransaction ft = MainActivity.this.getFragmentManager().beginTransaction();
                LedgerFrament f = new LedgerFrament();
                Bundle b = new Bundle();
                b.putString("layer_code", sbsModel.layer_code);
                b.putString("name", sbsModel.layer_name);
                f.setArguments(b);
                ft.replace(R.id.fragment_content, f);
                ft.commit();
            }
        });
        LinearLayout.LayoutParams rllp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.addView(arl1, rllp2);
        return arl1;
    }


    //-----------------------------------分割线 以上 by zhangjin---------------------------------------------------------------------204-719
    @Override
    public void onBackPressed() {
        Log.i(TAG, "onBackPressed");
        if (slideMenu.isMenuShowing()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("退出程序");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (NetUtil.isNetOK(getApplicationContext())) {
                        if (LocalDbDao.getInstance(getApplicationContext()).hasData())
                            MessageUtil.showPopDialog(getApplicationContext(), titleView, "上传", "有未上传结果，是否上传", "确定", UPLOAD_EXIT, MainActivity.this);
                        else F1Application.exit();
                    } else F1Application.exit();
                }
            });
            builder.show();
        } else {
            slideMenu.showMenu();

        }
    }

    //同步数据
    private void switchToMain() {
        showFragment(mainFragment);
        titleView.setRightTextView("同步数据");
        titleView.setRightImageViewVisibility(View.GONE);
        titleView.setTitle("我的任务");
        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                if (!NetUtil.isNetOK(getApplication())) {
                    MessageUtil.showPopDialog(getApplicationContext(), tv_username, "网络连接失败失败", "无法连接网络，请检测网络设置", "去设置", NO_NET_DIALOG, MainActivity.this);
                } else if (HttpCookies.getSessionId() == null || HttpCookies.getSessionId().equals("")) {
                    Log.i(TAG, "未登陆，在线验证");
                    MessageUtil.showLoginValidataPop(getApplicationContext(), tv_username, LOGIN_VALIDATA_DIALOG, MainActivity.this);
                } else
                    MessageUtil.show2RadioPop(MainActivity.this, titleView, UPDATE, MainActivity.this);
            }

            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                slideMenu.showMenu();
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_task:
                switchToMain();
                break;
            case R.id.ll_ledger:
                switchToLedger();

                break;
            case R.id.ll_regular_work:
                switchToRegular();
                break;
            case R.id.ll_check:
                showFragment(checkFragment);
                setTitleView();
                titleView.setTitle("点检管理");
                break;

            case R.id.ll_doc:
                setTitleView();
                showFragment(docFrament);
                titleView.setTitle("文档管理");
                break;

            case R.id.ll_setting:
                setTitleView();
                showFragment(settingFragment);
                titleView.setTitle("设置");
                break;
            case R.id.ll_exit:
                Log.i(TAG, "退出登录");
                sp.edit().putString(Constants.PERSON_GUID, "").commit();
                sp.edit().putString(Constants.PERSON_NAME, "").commit();
                sp.edit().putString(Constants.PERSON_LOGO_ID, "").commit();
                finish();
                break;
        }
    }

    /**
     * 切换至设备台账 fragment
     */
    private void switchToLedger(){
        titleView.setRightTextViewVisibility(View.GONE);
        titleView.setRightImageViewVisibility(View.VISIBLE);
        showFragment(nullFrament);
        titleView.setTitle("设备台账");
        slideMenu.setSecondaryMenu(rightMenuView);
        slideMenu.showSecondaryMenu();
        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                slideMenu.showMenu();
            }

            @Override
            public void onRightImage1Click(View view) {
                super.onRightImage1Click(view);
                slideMenu.setSecondaryMenu(rightMenuView);
                slideMenu.showSecondaryMenu();
            }
        });
    }

    /**
     * 切换至定期工作 fragment
     */
    private void switchToRegular(){
        showFragment(regularFragment);
        titleView.setRightTextView("筛选");
        titleView.setTitle("定期工作");
        titleView.setRightImageViewVisibility(View.GONE);
        slideMenu.setSecondaryMenu(rightMenuView2);
        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener(){
            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                slideMenu.showMenu();
            }

            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                slideMenu.setSecondaryMenu(rightMenuView2);
                slideMenu.showSecondaryMenu();
            }
        });

    }


    private void setTitleView() {
        titleView.setRightImageViewVisibility(View.GONE);
        titleView.setRightTextViewVisibility(View.GONE);
        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                slideMenu.showMenu();
            }
        });
    }

    public void upload() {
        if (dao.hasData()) {
            MessageUtil.showProgressDialog(MainActivity.this, "正在上传");
            if (dao.getRepeatResultnum() > 0) {
                String msg = "有" + dao.getRepeatResultnum() + "条重复上传记录，是否上传覆盖";
                MessageUtil.showRadioPop(getApplicationContext(), titleView, "提示", msg, "确定", REPEAT, MainActivity.this);
            } else {
                upLoadResultList = dao.getAllResult(true);
                new uploadReStatTask().execute();
//                new upLoadResultTask().execute();
//                new upLoadAbnormalTask().execute();
//                new upLoadDefectTask().execute();
                if (upLoadFileList.size() > 0)
                    for (int i = 0; i < upLoadFileList.size(); i++) {
                        new upLoadFileTask().execute(i);
                    }
            }
        } else {
            MessageUtil.showToast(this, "没有新的上传数据");
            Log.i(TAG, "choose = "+choose);
            //下载
            if(choose == 0){
                Log.i(TAG, "开始下载点检和台账数据...");
                //都下载
                new getCheckTask().execute();
                new getLedgerTask().execute();
            }else if(choose == 1){
                //只下载点检任务
                Log.i(TAG, "开始下载点检数据...");
                new getCheckTask().execute();
            }else if(choose == 2){
                //只下载台账数据
                Log.i(TAG, "开始下载台账...");
                new getLedgerTask().execute();
            }
        }
    }

    @Override
    public void onResult(int requsetViewId, Bundle bundle) {
        switch (requsetViewId) {

            case LOGIN_VALIDATA_DIALOG:   //在线验证弹窗监听
                String userName = bundle.getString("userName");
                new LoginTask().execute(userName, bundle.getString("pwd"));
                break;
            case NO_NET_DIALOG:   //无网络的弹窗监听
                if (!bundle.getBoolean("data")) {
                    return;
                }
                Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                startActivity(wifiSettingsIntent);
                break;
            case UPLOAD:  //上传点检结果
                if (!bundle.getBoolean("data")) {
                    return;
                }
                choose = -1;
                MessageUtil.showProgressDialog(MainActivity.this, "正在同步");
                if (dao.getRepeatResultnum() > 0) {
                    String msg = "有" + dao.getRepeatResultnum() + "条重复上传记录，是否上传覆盖";
                    MessageUtil.showRadioPop(getApplicationContext(), titleView, "提示", msg, "确定", REPEAT, MainActivity.this);
                } else {
                    upLoadResultList = dao.getAllResult(true);
                    new uploadReStatTask().execute();
//                    new upLoadResultTask().execute();
//                    new upLoadAbnormalTask().execute();
//                    new upLoadDefectTask().execute();
                    if (upLoadFileList.size() > 0) {
                        for (int i = 0; i < upLoadFileList.size(); i++) {
                            new upLoadFileTask().execute(i);
                        }
                    }
                }
                break;
            case UPDATE:  //同步
                choose = bundle.getInt("data", 0);
                Log.i(TAG, "i = "+choose);
                if (choose == 1) {//同步点检数据
                    Log.i(TAG, "只同步点检数据");
                    flag_update = 0;
                    MessageUtil.showProgressDialog2(MainActivity.this, "正在同步点检数据");
                    //先上传，后下载
                    upload();
//                    new getCheckTask().execute();

                } else if (choose == 2) {//只同步台账数据
                    flag_update = 1;
                    MessageUtil.showProgressDialog2(MainActivity.this, "正在同步台账数据");
                    Log.i(TAG, "只同步台账数据");
                    //先上传，后下载
                    upload();
//                    new getLedgerTask().execute();

                } else if (choose == 3) {//都不同步
                    MessageUtil.showToast(getApplicationContext(), "请至少勾选一项");
                } else {
                    flag_update = 1;
                    Log.i(TAG, "同时同步台账和点检");
                    MessageUtil.showProgressDialog2(MainActivity.this, "正在同步台账和点检数据");
                    //先上传，后下载
                    upload();
//                    new getCheckTask().execute();
//                    new getLedgerTask().execute();
                }
                break;
            case REPEAT:  //是否上传覆盖
                MessageUtil.showProgressDialog(MainActivity.this, "正在上传");
                upLoadResultList = dao.getAllResult(bundle.getBoolean("repeat", true));
                new uploadReStatTask().execute();
//                new upLoadResultTask().execute();
//                new upLoadAbnormalTask().execute();
//                new upLoadDefectTask().execute();
                if (upLoadFileList.size() > 0) {
                    for (int i = 0; i < upLoadFileList.size(); i++) {
                        new upLoadFileTask().execute(i);
                    }
                }
                break;
            case UPLOAD_EXIT:
                if (!bundle.getBoolean("data")) {
                    F1Application.exit();
                }
                MessageUtil.showProgressDialog(MainActivity.this, "正在同步");
                if (dao.getRepeatResultnum() > 0) {
                    String msg = "有" + dao.getRepeatResultnum() + "条重复上传记录，是否上传覆盖";
                    MessageUtil.showRadioPop(getApplicationContext(), titleView, "提示", msg, "确定", REPEAT, MainActivity.this);
                } else {
                    upLoadResultList = dao.getAllResult(true);

                    new uploadReStatTask().execute();
//                    new upLoadResultTask().execute();
//                    new upLoadAbnormalTask().execute();
//                    new upLoadDefectTask().execute();
                    if (upLoadFileList.size() > 0) {
                        for (int i = 0; i < upLoadFileList.size(); i++) {
                            new upLoadFileTask().execute(i);
                        }
                    }
                }
                break;
        }
    }

    /**
     * 上传统计结果task
     * （1）计算统计数据表中的值;
     * （2）存到本地数据表中;
     * （2）上传至服务器；
     */
    private class uploadReStatTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            //（1）计算统计数据表中的值;
            String uploadReStat = null;
            try {
                uploadReStat = computeReStat();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String url = AppConfig.BASE_URL + Constants.UPLOAD_RESULT_STATISTIC_URL;
            Log.i(TAG, "上传统计结果URL：" + url);
            Map<String, String> map = new HashMap<>();
            String param = uploadReStat;
            map.put("list", param);
            Log.i(TAG, "上传统计结果参数：" + param);
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject json = new JSONObject(s);
                int code = json.getInt("code");
                if (code == -1) {
                    //     MessageUtil.showToast(getApplicationContext(), json.getString("hint"));
                } else {
                    MessageUtil.showToast(getApplication(), "统计结果上传成功");
                    Log.i(TAG, "统计结果上传成功");
                    Log.i(TAG, "开始上传点检结果......");
                    new upLoadResultTask().execute();
                    showFragment(new MainFragment());
                }

            } catch (JSONException e) {
                e.printStackTrace();
                MessageUtil.showToast(getApplicationContext(), "未知错误");
            }
        }
    }

    /**
     * （1）计算统计数据表中的值
     * （2）存在数据库中
     * （3）生成待上传字符串
     *
     * @return
     */
    private String computeReStat() throws JSONException {
        String result = "";

        // 计算统计表中的值，并存储在数据库中

        InsertDb db = InsertDb.getInstance(MainActivity.this);
        // 获取7天内，当前用户的所有任务（仅task id）
        String userId = sp.getString(Constants.PERSON_GUID, "");
        List<String> taskIds = db.getRecentTask(userId);

        // 把一系列id生成一个字符串
        List<ResultStatisticModel> statistic =
                LocalDbDao.getInstance(MainActivity.this).calStatistic(userId, taskIds);

        // 存储到数据库
        db.insertOrUpdateStatistic(statistic);

        // 生成待上传字符串
        JSONObject json = statisticToJSONObject(statistic);

        return json.toString();
    }

    /**
     * 统计结果，生成待上传的JSONObject
     *
     * @param list
     * @return
     * @throws JSONException
     */
    private JSONObject statisticToJSONObject(List<ResultStatisticModel> list) throws JSONException {
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();

        if (list != null) {
            for (ResultStatisticModel model : list) {
                JSONObject tmp = new JSONObject();
                tmp.put("task_id", model.task_id);
                tmp.put("total_must_si_com_num", model.total_must_si_com_num);
                tmp.put("total_must_si_forgot_num", model.total_must_si_forgot_num);
                tmp.put("total_si_num", model.total_si_num);
                tmp.put("total_forgot_num", model.total_forgot_num);
                tmp.put("si_person", model.si_person);
                tmp.put("si_time", model.si_time);
                tmp.put("upload_time", model.upload_time);
                tmp.put("YC_COUNT", model.YC_COUNT);
                tmp.put("QX_COUNT", model.QX_COUNT);
                array.put(tmp);
            }
        }

        object.put("list", array);

        return object;
    }

    /**
     * 把一系列id生成一个字符串
     *
     * @param ids {List<String>}
     * @return 格式('id1', 'id2', 'id3', ..., 'idn')
     */
    private String genOneIdParam(List<String> ids) {
        if (ids == null || ids.size() == 0) return "()";
        StringBuilder builder = new StringBuilder("(");
        for (String id : ids) {
            builder.append("'").append(id).append("',");
        }
        builder.deleteCharAt(builder.length() - 1);
        builder.append(")");
        return builder.toString();
    }

    private class upLoadResultTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.UPLOAD_RESULT_URL;
            Log.i(TAG, "上传结果URL：" + url);
            Map<String, String> map = new HashMap<>();
            String list = "";
            List sublist = null;
            String param = "";
            String result = "";
            int length = upLoadResultList.size();
            Log.i(TAG, "要上传的点检结果数为：" + length);
            int count = length / 1000;
            Log.i(TAG, "需要上传次数为：" + (count + 1));
            for (int i = 0; i <= count; i++) {
                Log.i(TAG, "第" + (i + 1) + "次");
                if (i < count)
                    sublist = upLoadResultList.subList(i * 1000, i * 1000 + 1000);
                else
                    sublist = upLoadResultList.subList(i * 1000, length);

                list = gson.toJson(sublist);
                param = "{\"list\":" + list + "}";
                map.put("list", param);
                Log.i(TAG, "上传点检结果参数map：" + map.toString());
                result = new HttpClient(getApplicationContext()).doPost(url, map);
                Log.i(TAG, "上传点检结果返回结果：" + result);
            }

            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject json = new JSONObject(s);
                int code = json.getInt("code");
                if (code == -1) {
                    MessageUtil.showToast(getApplicationContext(),"点检结果上传失败");
                } else {
                    //删除点检结果暂存表中的数据
                    dao.delectALLResult();
                    //删除同步数据库中三天前的点检数据
                    db.deleteHisCheckRes();
                    showFragment(new MainFragment());
                    MessageUtil.showToast(getApplicationContext(),"点检结果上传成功");
                    Log.i(TAG, "点检结果上传成功");
                    Log.i(TAG, "开始上传异常结果...");
                    new upLoadAbnormalTask().execute();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class upLoadAbnormalTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.UPLOAD_ABNORMAL_URL;
            Log.i(TAG, "上传异常URL：" + url);
            Map<String, String> map = new HashMap<>();
            String list = gson.toJson(upLoadabnormalList);
            String param = "{\"list\":" + list + "}";
            Log.i(TAG, "上传异常参数：" + param);
            map.put("list", param);
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "上传异常返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject json = new JSONObject(s);
                int code = json.getInt("code");
                if (code == -1) {
                    //  MessageUtil.showToast(getApplicationContext(), json.getString("hint"));
                    dao.delectALLAbnormal();
                    Log.i(TAG, "上传异常失败");
                } else {
                    Log.i(TAG, "上传异常成功");
                    MessageUtil.showToast(getApplicationContext(), "上传异常结果成功");
                    dao.delectALLAbnormal();
                    Log.i(TAG, "开始上传缺陷结果...");
                    new upLoadDefectTask().execute();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class upLoadDefectTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.UPLOAD_DEFECT_URL;
            Log.i(TAG, "上传缺陷URL：" + url);
            Map<String, String> map = new HashMap<>();
            String list = gson.toJson(upLoadDefectList);
            String param = "{\"list\":" + list + "}";
            Log.i(TAG, "上传缺陷参数：" + param);
            map.put("list", param);
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "上传缺陷返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.startsWith("606")) {
                MessageUtil.dismissProgressDialog();
                MessageUtil.showToast(getApplicationContext(), "该账号已在其它地方登陆");
                return;
            }
            dao.delectALLDefect();
            try {
                JSONObject json = new JSONObject(s);
                int code = json.getInt("code");
                if (code == -1) {
                    MessageUtil.dismissProgressDialog();
                    MessageUtil.showToast(getApplicationContext(), json.getString("hint"));
                    Log.i(TAG, "上传缺陷失败");
                } else {
                    MessageUtil.dismissProgressDialog();
                    MessageUtil.showToast(getApplicationContext(), "上传缺陷成功");
                    Log.i(TAG, "上传缺陷成功");
                    dao.delectALLDefect();

                    Log.i(TAG, "choose = "+choose);
                    //下载
                    if(choose == 0){
                        Log.i(TAG, "开始下载点检和台账数据...");
                        //都下载
                        new getCheckTask().execute();
                        new getLedgerTask().execute();
                    }else if(choose == 1){
                        //只下载点检任务
                        Log.i(TAG, "开始下载点检数据...");
                        new getCheckTask().execute();
                    }else if(choose == 2){
                        //只下载台账数据
                        Log.i(TAG, "开始下载台账...");
                        new getLedgerTask().execute();
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class upLoadFileTask extends AsyncTask<Integer, Void, Integer> {

        @Override
        protected Integer doInBackground(Integer... params) {
            FileLbModel model = upLoadFileList.get(params[0]);
            Log.i(TAG, "上传文件名:" + model.wjmc);
            Boolean result = new HttpClient(getApplicationContext()).upLoadFile(model);
            Log.i(TAG, "上传文件返回结果：" + result);
            return params[0];
        }

        @Override
        protected void onPostExecute(Integer s) {
            super.onPostExecute(s);
            if (s == upLoadFileList.size() - 1) {
                MessageUtil.dismissProgressDialog();
                MessageUtil.showToast(getApplicationContext(), "上传文件成功");
                dao.delectAllFile();
            }
        }
    }

    /**
     * 下载台账数据
     */
    private class getLedgerTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.UPDATE_LEDGER_URL;
            Log.i(TAG, "同步台账相关数据URL：" + url);
            Map<String, String> map = new HashMap<>();
            map.put("user_id", F1Application.getUserId());
            //map.put("timepoint", "2016-04-20 13:57:00");
            map.put("timepoint", F1Application.getLedgerUpdateTime());
            Log.i(TAG, "台账时间戳：" + F1Application.getLedgerUpdateTime());
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "同步台账相关数据结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.startsWith("606")) {
                MessageUtil.dismissProgressDialog();
                MessageUtil.showToast(getApplicationContext(), "该账号已在其它地方登陆");
                return;
            }
            try {  //写入数据库
                UpdateLedger4Json uc4j = gson.fromJson(s, new TypeToken<UpdateLedger4Json>() {
                }.getType());
                outputLog(uc4j);
                InsertDb.getInstance(getApplicationContext()).insertLedger(uc4j);
                fileList = uc4j.tb_file_lb;
                MessageUtil.dismissProgressDialog2();
                F1Application.setLedgerUpdateTime();
                Log.i(TAG, "解析台账数据成功");
                MessageUtil.showToast(getApplicationContext(), "台账数据下载成功");
            } catch (Exception e) {
                Log.i(TAG, "解析台账数据异常");
                MessageUtil.dismissProgressDialog2();
                e.printStackTrace();
            }
        }

        /**
         * 输出台账同步接口返回的数据
         *
         * @param uc4j
         */
        private void outputLog(UpdateLedger4Json uc4j) {
            Log.i(TAG, "uc4j.tb_bz_bzgl " + uc4j.tb_bz_bzgl.size() + "");
            Log.i(TAG, "uc4j.tb_bz_bzgls " + uc4j.tb_bz_bzgls.size() + "");
            Log.i(TAG, "uc4j.tb_eq_abnormal " + uc4j.tb_eq_abnormal.size() + "");
            Log.i(TAG, "uc4j.tb_eq_attacheq " + uc4j.tb_eq_attacheq.size() + "");
            Log.i(TAG, "uc4j.tb_eq_basicinfo " + uc4j.tb_eq_basicinfo.size() + "");
            Log.i(TAG, "uc4j.tb_eq_defect " + uc4j.tb_eq_defect.size() + "");
            Log.i(TAG, "uc4j.tb_eq_defect_type " + uc4j.tb_eq_defect_type.size() + "");
            Log.i(TAG, "uc4j.tb_eq_dept_form " + uc4j.tb_eq_dept_form.size() + "");
            Log.i(TAG, "uc4j.tb_eq_files " + uc4j.tb_eq_files.size() + "");
            Log.i(TAG, "uc4j.tb_file_eq_ref " + uc4j.tb_file_eq_ref.size() + "");
            Log.i(TAG, "uc4j.tb_eq_form_customfields " + uc4j.tb_eq_form_customfields.size() + "");
            Log.i(TAG, "uc4j.tb_eq_form_customfields_value " + uc4j.tb_eq_form_customfields_value.size() + "");
            Log.i(TAG, "uc4j.tb_eq_form_stdfields " + uc4j.tb_eq_form_stdfields.size() + "");
            Log.i(TAG, "uc4j.tb_eq_maintenance " + uc4j.tb_eq_maintenance.size() + "");
            Log.i(TAG, "uc4j.tb_eq_relayaction " + uc4j.tb_eq_relayaction.size() + "");
            Log.i(TAG, "uc4j.tb_eq_tuotui " + uc4j.tb_eq_tuotui.size() + "");
        }
    }

    private class getCheckTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.UPDATE_CHECK_URL;
            Log.i(TAG, "下载今日点检任务URL：" + url);
            Map<String, String> map = new HashMap<>();
            map.put("user_id", F1Application.getUserId());
            //map.put("timepoint", "2016-01-02 10:58:37");
            String timepoint = F1Application.getDbUpdateDate(F1Application.getUserId());
            Log.i(TAG, "下载今日点检任务时间戳：" + timepoint);
            map.put("timepoint", timepoint);
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "下载今日点检任务返回結果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
//            Log.i(TAG, "s == " + s);
            super.onPostExecute(s);
            //写入数据库
            if (s.startsWith("606")) {
                MessageUtil.dismissProgressDialog();
                MessageUtil.showToast(getApplicationContext(), "该账号已在其它地方登陆");
                return;
            }
            UpdateCheck4Json uc4j = null;
            try {
                uc4j = gson.fromJson(s, new TypeToken<UpdateCheck4Json>() {
                }.getType());
            } catch (Exception e) {
                Log.e(TAG, "解析json数据时发生异常");
                MessageUtil.dismissProgressDialog2();
                /*if (s.contains("601")) {
                    MessageUtil.showToastDialog(MainActivity.this, "提示", "登录已过期，请重新登录");
                }*/
            }
            if (uc4j != null) {
                if (uc4j.tb_si_task == null || uc4j.tb_si_task.size() == 0) {
                    MessageUtil.dismissProgressDialog2();
                    MessageUtil.showToast(getApplication(), "今日无新任务");
                    F1Application.setDBUpdateDate(F1Application.getUserId());

                } else {
                    InsertDb insertDb = InsertDb.getInstance(getApplicationContext());
                    insertDb.insertTaskResult(uc4j.tb_si_task_result);
                    insertDb.insertTask(uc4j.tb_si_task);
                    insertDb.insertPos(uc4j.tb_dev_ins_position);
                    taskModelList = uc4j.tb_si_task;
                    Log.i(TAG, "taskModelList 长度" + taskModelList.size());
                    new UpdateTaskStatus().execute();
                    for (TaskModel model : uc4j.tb_si_task) {
                        ModifyDb.getInstance(getApplicationContext()).setTaskStatus(model.guid, "未完成");
                    }
                    Log.i(TAG, "解析点检数据成功");
                    MessageUtil.showToast(getApplicationContext(), "点检任务下载成功");
                    F1Application.setDBUpdateDate(F1Application.getUserId());
                    showFragment(new MainFragment());

                    if (flag_update == 0)
                        MessageUtil.dismissProgressDialog2();
                }
            } else {
                MessageUtil.showToastDialog(MainActivity.this, "提示", "数据格式错误，请联系服务端人员");
            }


        }
    }

    private class LoginTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.LOGIN_URL;
            // Log.i(TAG, "登陆url：" + url);
            String result = "";
            Map<String, String> map = new HashMap<>();
            map.put("username", params[0]);
            map.put("password", params[1]);
            map.put("pageStyle", "");
            map.put("logined", params[0]);
            map.put("agent", "1");
            result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "登陆返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            try {
                User4Json uj = gson.fromJson(s, new TypeToken<User4Json>() {
                }.getType());
                if (uj.successful.equals("true")) {
                    MessageUtil.showToast(getApplicationContext(), "验证成功");
                    F1Application.setUserName(uj.resultValue.persName);
                    F1Application.setUserId(uj.resultValue.persGuid);
                    MessageUtil.show2RadioPop(getApplicationContext(), tv_username, UPDATE, MainActivity.this);
                } else {
                    MessageUtil.showToast(getApplicationContext(), uj.resultHint);
                    HttpCookies.setSessionId(null);
                }
            } catch (Exception e) {
                MessageUtil.showToast(getApplicationContext(), "验证失败");
            }
        }
    }

    class UpdateTaskStatus extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            StringBuffer list = new StringBuffer();
            list.append("{\"list\":[");
            for (int i = 0; i < taskModelList.size(); i++) {
                list.append("{\"task_id\":");
                list.append("\"");
                list.append(taskModelList.get(i).guid);
                list.append("\"");
                list.append(",");
                list.append("\"task_status\":\"已下载\"}");
                if (i < taskModelList.size() - 1) {
                    list.append(",");
                }
            }
            list.append("]}");
            Log.i(TAG, "上传任务状态参数：" + list);
            String url = AppConfig.BASE_URL + Constants.UPLOAD_TASK_STATUS_URL;
            Log.i(TAG, "上传任务状态url:" + url);
            Map<String, String> map = new HashMap<>();
            map.put("list", list.toString());
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "上传任务状态返回结果:" + result);
            return null;
        }
    }


    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    public void notifyReloadFragment() {
        showFragment(new SettingFragment());
    }


}